package org.leetcode.middle.leetcode238;

import java.util.Arrays;

public class Solution {


    public int[] productExceptSelf3(int[] nums)
    {
        int length =nums.length;

        int [] res= new int[length];

        int [] Left = new int[length];

        int [] Right = new int[length];

        Left[0]=1;
        Right[length-1]=1;

        for (int i = 1; i <nums.length; i++) {
            Left[i]=Left[i-1]*nums[i-1];
        }

        for (int i = length-2; i >0; i--) {
            Right[i]=Right[i+1]*nums[i+1];
        }

        for (int i = 0; i < length; i++) {
            res[i]=Left[i]*Right[i];
        }

        return res;

    }


    //没看明白
    public int[] productExceptSelf2(int[] nums) {
        int n=nums.length;
        int[] ans=new int[n];
        Arrays.fill(ans,1);
        int beforeSum=1;
        int afterSum=1;
        for(int i=0,j=n-1;i<n;i++,j--){
            ans[i]*=beforeSum;
            ans[j]*=afterSum;
            beforeSum*=nums[i];
            afterSum*=nums[j];
        }
        return ans;
    }
    public int[] productExceptSelf(int[] nums) {

        int [] res= new int [nums.length];

        Arrays.fill(res,1);

        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (i==j) {
                    continue;
                }else if (nums[j]==0) {
                    res[i]=0;
                    break;
                }else {
                    res[i]=nums[j]*res[i];
                }
            }
        }

        return res;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        int [] test ={1,2,3,4};

        int[] res = solution.productExceptSelf2(test);
        System.out.println(res);
    }
}
